﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace Npu_Platform
{
    public partial class ServerForm : Form
    {
        Server server;
        delegate void SetTextCallback(String Text);
        delegate void MessageBoxCallback(Exception Ex);
        public ServerForm()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
            ServerIpa.Text = IpEntry.AddressList[0].ToString();
            server = new Server(IPAddress.Parse(ServerIpa.Text), int.Parse(Port.Text));
            server.SendMessage += new Server.SendMessageEventHandler(DisplayMessage);
            server.SendError += new Server.SendErrorEventHandler(DisplayError);

        }

        private void button1_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(Receive));
        }

        private void Receive(Object stateInfo)
        {
            server.ServerInit();
        }
        public void ShowError(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        public void DisplayError(Exception ex)
        {
            ServerForm.MessageBoxCallback d = new ServerForm.MessageBoxCallback(ShowError);
        }
        public void DisplayMessage(String s)
        {
            ServerForm.SetTextCallback d = new ServerForm.SetTextCallback(ShowMessage);
            this.Invoke(d, new object[] { s });
        }
        public void ShowMessage(String s)
        {
            MessageText.Text += s + "\r\n";
        }
    }
}
